**this do file defines all programs for main result regressions** 

preserve 
use "$stata\CAFC_ct_updated.dta", clear
sum gap_all 
global gap_mean = r(mean)
restore

*Setting up programs 
capture program drop get_coef
program define get_coef
	quietly {  
	 `1' , absorb($fe)  
	 scalar nobs = e(N) 
	 capture scalar rsq = e(r2_a)
	 capture scalar rsq_p = e(r2_p)
	 capture scalar rsq_within = e(r2_a_within) 
	 capture scalar chi2 = e(chi2)
	 unique gvkey if e(sample) == 1
	 scalar cmp = `r(unique)'
	 lincom CAFC_post *$gap_mean 
	 local est = r(estimate)
	 local change = (exp(`est')-1)*100
	 scalar perct = `change'
	 matrix coef = e(b) 
	}   
end 
 
capture program drop reg_out 
program define reg_out 
cd "$stataout"
outreg2 using "`1'", word  nor2 noobs  /// 
      addtext("Technology-Year-Industry", "Yes", "Circuit FE", "Yes") ///
	addstat( "Companies", cmp, "Adjusted R-squared", rsq, ///
	"Within R-squared", rsq_within ,   "Economic effect", perct) ///
	 sortvar(_b_CAFC_post  _b_emp_ln _b_revt_per_inh _b_ppe_per_inh ///
	 _b_nclaims _b_novelty_res_inh  _b_nciting_inh _b_pcs_inh ///
	  _b_cons) bdec(3) tdec(3)  ctitle("`2'")
matrix drop _all 
scalar drop _all 
end 

capture program drop reg_out_count
program define reg_out_count 
cd "$stataout"
outreg2 using "`1'", word  nor2 noobs  /// 
      addtext("Technology-Year-Industry", "Yes", "Circuit FE", "Yes") ///
	addstat( "Companies", cmp, "Chi-squared", chi2, ///
	  "Economic effect", perct) ///
	 sortvar(_b_CAFC  _b_emp_ln _b_revt_per_inh _b_ppe_per_inh ///
	 _b_nclaims _b_novelty_res_inh  _b_nciting_inh _b_pcs_inh ///
	  _b_cons) bdec(3) tdec(3)  ctitle("`2'")
matrix drop _all 
scalar drop _all 
end 

global sample1 if !mi(subcat) & !mi(circuit) 

capture program drop tse_boot  
program tse_boot, eclass  
	quietly {  
		use "$stata\CAFC\CAFC_reg.dta", clear  
		preserve  
		bsample, strata(ct_post)    
		xi: ologit outcome patdef claims ass home_circuit appeal  ///
		ct1 ct2 ct4-ct10 cafcct1-cafcct11 hjt1-hjt5 i.year ///
		$sample1, robust

		foreach j in 1 2 4 5 6 7 8 9 10{
		replace ratepre_all = _b[ct`j'] if circuit == `j'
		quietly lincom ct`j' +   cafcct`j'   
		replace ratepost_all = `r(estimate)' if circuit == `j' 
		}

		replace ratepre_all = 0 if circuit == 3
		replace ratepost_all = _b[cafcct3] if circuit == 3
		replace ratepre_all = _b[ct5] if circuit == 11
		replace ratepost_all = _b[cafcct11] if circuit == 11
		
		gen gap_all = ratepost_all - ratepre_all 
		keep circuit gap_all 
		duplicates drop 
		tempfile temp
		save `temp', replace
		restore  

		use "$stata\CAFC\Patreg.dta", clear
		preserve  
		bsample  , cluster(gvkey circuit)
		merge m:1 circuit using `temp', update replace 
		replace CAFC = gap_all * post 
		 `1',  absorb($fe) 
		restore 
	 }  
end  
